package com.yayo.mangement.executors;

import com.yayo.mangement.authentication.annotations.ExcelExport;
import com.yayo.mangement.iface.XlsxExporter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * XlsxExporter实现类注册
 *
 * @author Yayo
 * @date 2020/07/01
 */
@Component
@Configuration
@Slf4j
public class ExcelExecutorRegister implements ApplicationContextAware {

    private final Map<String, XlsxExporter> SERVICE_MAP = new LinkedHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, XlsxExporter> xlsxExporterMap = applicationContext.getBeansOfType(XlsxExporter.class);
        if (!CollectionUtils.isEmpty(xlsxExporterMap)) {
            xlsxExporterMap.forEach((key, exporter) -> {
                ExcelExport excelExport = exporter.getClass().getAnnotation(ExcelExport.class);
                log.info("Excel executor regist named: {}", excelExport.code());
                SERVICE_MAP.put(excelExport.code(), exporter);
            });
        }
    }

    public XlsxExporter getXlsxExporter(String name) {
        return Optional.ofNullable(SERVICE_MAP.get(name)).orElseThrow((Supplier<RuntimeException>) () -> new RuntimeException("export.not.exists : " + name));
    }

}
